/********************************** (C) COPYRIGHT *******************************
 * File Name          : ch32v30x_it.c
 * Author             : WCH
 * Version            : V1.0.0
 * Date               : 2024/03/05
 * Description        : Main Interrupt Service Routines.
 *********************************************************************************
 * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
 * Attention: This software (modified or not) and binary are used for
 * microcontroller manufactured by Nanjing Qinheng Microelectronics.
 *******************************************************************************/
#include "ch32v30x_it.h"
#include "RMII_eth_driver.h"
#include "netconf.h"
#include "ethernetif.h"

#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"

extern xSemaphoreHandle g_rx_semaphore;

void NMI_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
void HardFault_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
void ETH_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));

/*********************************************************************
 * @fn      NMI_Handler
 *
 * @brief   This function handles NMI exception.
 *
 * @return  none
 */
void NMI_Handler(void)
{
    while (1) {
    }
}

/*********************************************************************
 * @fn      HardFault_Handler
 *
 * @brief   This function handles Hard Fault exception.
 *
 * @return  none
 */
void HardFault_Handler(void)
{
    // NVIC_SystemReset();
    while (1) {
    }
}

/*********************************************************************
 * @fn      ETH_IRQHandler
 *
 * @brief   This function handles ETH exception.
 *
 * @return  none
 */
void ETH_IRQHandler(void)
{
    portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;

    if (ETH->DMASR & ETH_DMA_IT_R) {
        xSemaphoreGiveFromISR(g_rx_semaphore, &xHigherPriorityTaskWoken);
        ETH_DMAClearITPendingBit(ETH_DMA_IT_R);
    }
    if (ETH->DMASR & ETH_DMA_IT_T) {
        ETH_DMAClearITPendingBit(ETH_DMA_IT_T);
    }
    ETH_DMAClearITPendingBit(ETH_DMA_IT_NIS);

    /* switch tasks if necessary */
    if (pdFALSE != xHigherPriorityTaskWoken) {
        portEND_SWITCHING_ISR(xHigherPriorityTaskWoken);
    }
}